// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function() { // 通用预处理器

	},
	/* 获取题库列表 */
	async storehouse(pageNo, pageSize, type) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		return await dbJQL.collection("questions-storehouse").where({
				flag: false,
				type
			})
			.orderBy('year', 'desc')
			.skip((pageNo - 1) * pageSize)
			.limit(pageSize)
			.get()
	},
	/* 发布题库 */
	async storehouse_publish(params) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		let reference = dbJQL.collection('questions-storehouse')
		if (params._id) { // 更新
			return await reference.doc(params._id).update({
				title: params.title,
				year: params.year
			})
		} else { // 新增
			return await reference.add({
				title: params.title,
				year: params.year,
				type: params.type
			})
		}
	},
	/* 删除题库 */
	async storehouse_delete(id) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		return await dbJQL.collection('questions-storehouse').doc(id).update({
			flag: true
		})
	},
	/* 获取题库详情 */
	async storehouse_detail_simple(docID) {
		console.log(docID);
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		return await dbJQL.collection("questions-storehouse").doc(docID).get({
			getOne: true
		})
	},
	/* 获取单个题库所有题目详情 */
	async storehouse_detail(question_storehouse_id) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const dbCmd = dbJQL.command
		const $ = dbCmd.aggregate
		return await dbJQL.collection("questions-topic").aggregate()
			.match({
				question_storehouse_id
			})
			.lookup({
				from: 'topic-options',
				let: {
					topic_id: '$_id'
				},
				pipeline: $.pipeline().match(
					dbCmd.expr($.eq(['$topic_id', '$$topic_id']))
				).done(),
				as: 'options'
			})
			.lookup({
				from: 'favorite',
				let: {
					article_id: '$_id'
				},
				pipeline: $.pipeline().match(
					dbCmd.expr($.eq(['$article_id', '$$article_id']))
				).count('count').done(),
				as: 'is_like'
			})
			.lookup({
				from: 'opendb-note',
				let: {
					topic_id: '$_id'
				},
				pipeline: $.pipeline().match(
					dbCmd.expr($.and([
						$.eq(['$topic_id', '$$topic_id']),
						$.eq(['$flag', false]),
						$.eq(['$user_id', dbJQL.getCloudEnv('$cloudEnv_uid')])
					]))
				).done(),
				as: 'note'
			})
			.project({
				analysis: 1,
				answer: 1,
				difficulty: 1,
				options: 1,
				note: $.arrayElemAt(['$note', 0]),
				question_content: 1,
				question_storehouse_id: 1,
				answer_fill_blanks: 1,
				question_type: 1,
				is_like: $.cond({
					if: $.gt([$.arrayElemAt(['$is_like.count', 0]), 0]),
					then: true,
					else: false
				})
			})
			.end()
	},
	/* 获取题目列表 */
	async topic(question_storehouse_id, pageNo, pageSize) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		return await dbJQL.collection("questions-topic")
			.where(`question_storehouse_id=='${question_storehouse_id}' && flag == false`)
			.skip((pageNo - 1) * pageSize)
			.limit(pageSize)
			.get()
	},
	/* 获取单个题目详情 */
	async topic_publish_detail(_id) {
		const dbJQL = uniCloud.databaseForJQL()
		const dbCmd = dbJQL.command
		const $ = dbCmd.aggregate
		return await dbJQL.collection("questions-topic").aggregate()
			.match({
				_id,
				flag: false
			})
			.lookup({
				from: 'topic-options',
				let: {
					topic_id: '$_id'
				},
				pipeline: $.pipeline().match(
					dbCmd.expr($.eq(['$topic_id', '$$topic_id']))
				).done(),
				as: 'options'
			})
			.end()
	},
	/* 发布题目 */
	async topic_publish(params) {
		console.log('topic_publish', params);
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		// 链接表
		let reference_topic = dbJQL.collection('questions-topic')
		let reference_options = dbJQL.collection('topic-options')
		// 返回值
		let result
		if (params._id) { // 更新
			result = await reference_topic.doc(params._id).update({
				question_content: params.question_content,
				question_type: params.question_type,
				difficulty: params.difficulty,
				analysis: params.analysis,
				answer: params.answer,
				answer_fill_blanks: params.answer_fill_blanks
			})
			if (result.errCode != 0) {
				return result
			}
		} else { // 新增
			result = await reference_topic.add({
				question_storehouse_id: params.question_storehouse_id,
				question_content: params.question_content,
				question_type: params.question_type,
				difficulty: params.difficulty,
				analysis: params.analysis,
				answer: params.answer,
				answer_fill_blanks: params.answer_fill_blanks
			})
			if (result.errCode != 0) {
				return result
			}
			// 记录当前这条数据的id
			params._id = result.id
			// 给选项记录topic_id
			if (params.options) {
				params.options.forEach(item => {
					item.topic_id = params._id
				})
			}
		}
		// 移除旧的选项
		result = await reference_options.where(`topic_id=="${params._id}"`).remove()
		if (result.errCode != 0) {
			return result
		}
		if (params.options?.length > 0) {
			// 新增新的选项
			params.options.forEach(item => {
				delete item._id
				delete item.create_date
			})
			return await reference_options.add(params.options)
		}
		return result
	},
	/* 删除题目 */
	async topic_delete(id) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		// 删除questions-topic
		return await dbJQL.collection('questions-topic').doc(id).update({
			flag: true
		})
	},
	/* 获取题目详情 */
	async topic_detail(id) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		const dbCmd = dbJQL.command
		const $ = dbCmd.aggregate
		return dbJQL.collection('questions-topic').aggregate()
			.match({
				_id: id
			})
			.lookup({
				from: 'topic-options',
				let: {
					topic_id: '$_id'
				},
				pipeline: $.pipeline().match(
					dbCmd.expr($.eq(['$topic_id', '$$topic_id']))
				).done(),
				as: 'options'
			})
			.lookup({
				from: 'favorite',
				let: {
					article_id: '$_id'
				},
				pipeline: $.pipeline().match(
					dbCmd.expr($.eq(['$article_id', '$$article_id']))
				).count('count').done(),
				as: 'is_like'
			})
			.project({
				analysis: 1,
				answer: 1,
				difficulty: 1,
				is_like: $.cond({
					if: $.gt([$.arrayElemAt(['$is_like.count', 0]), 0]),
					then: true,
					else: false
				}),
				options: 1,
				question_content: 1,
				question_storehouse_id: 1,
				question_type: 1
			})
			.end()
	}
}